package cn.itsource.basic.interceptor;

import cn.itsource.basic.annotation.PreAuthorize;
import cn.itsource.basic.domain.LoginData;
import cn.itsource.basic.jwt.JwtUtils;
import cn.itsource.basic.jwt.Payload;
import cn.itsource.basic.jwt.RsaUtils;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.org.domain.Logininfo;
import cn.itsource.system.mapper.PermissionMapper;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 前置拦截器
     * @param request
     * @param response
     * @param handler
     * @return 返回ture表示放行，false表示拦截
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取token
        String token = request.getHeader("U-TOKEN");
        //拿token去redis中查用户的登录状态
        Logininfo logininfo = null;
        List<String> permissions = new ArrayList<>();
        if(token != null){
            //解密jwt
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            Payload<LoginData> payload = null;
            try {
                payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
            } catch (Exception e) {
                e.printStackTrace();
                //登录检查
                response.setContentType("application/json;charset=utf-8");
                response.setCharacterEncoding("utf-8");
                //获取响应流
                PrintWriter writer = response.getWriter();
                //创建Ajaxresult对象
                AjaxResult noLogin = AjaxResult.me().setSuccess(false).setMessage("noLogin");
                writer.write(JSON.toJSONString(noLogin));
                writer.flush();
                writer.close();
                return false;
            }
            //拿到加密的数据
            LoginData userInfo = payload.getUserInfo();
            logininfo = userInfo.getLogininfo();
            permissions = userInfo.getPermissions();

        }
        //如果没有，返回Ajaxresult，定义字符串提示前端需要跳转到登录页.
        //TODO 查看当前用户是否有访问目标方法的权限 已知：这里是可以获取到访问的目标的方法的
        //如果是门户站只检查登录，不检查权限
        if(logininfo.getType() == 1){
            return true;
        }
        //获取访问的目标方法
        HandlerMethod method = (HandlerMethod)handler;
        //查看目标方法上是否加了注解
        PreAuthorize methodAnnotation = method.getMethodAnnotation(PreAuthorize.class);
        //获取到的注解不为空
        if(methodAnnotation != null){
            //访问方法需要的sn
            String sn = methodAnnotation.value();
            //判断查询出来的sn是否包含目标方法的sn
            if(!permissions.contains(sn)){
                //不包含那么就表示没有权限访问
                response.setContentType("application/json;charset=utf-8");
                response.setCharacterEncoding("utf-8");
                //获取响应流
                PrintWriter writer = response.getWriter();
                //创建Ajaxresult对象
                AjaxResult noLogin = AjaxResult.me().setSuccess(false).setMessage("没有权限访问！！！");
                writer.write(JSON.toJSONString(noLogin));
                writer.flush();
                writer.close();
                return false;
            }
        }
        //如果有就放行
        return true;
    }

//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //从请求头中获取token
//        String token = request.getHeader("U-TOKEN");
//        //拿token去redis中查用户的登录状态
//        Object logininfo = null;
//        if(token != null){
//            logininfo = redisTemplate.opsForValue().get(token);
//        }
//        //如果没有，返回Ajaxresult，定义字符串提示前端需要跳转到登录页.
//        if(logininfo == null){
//            response.setContentType("application/json;charset=utf-8");
//            response.setCharacterEncoding("utf-8");
//            //获取响应流
//            PrintWriter writer = response.getWriter();
//            //创建Ajaxresult对象
//            AjaxResult noLogin = AjaxResult.me().setSuccess(false).setMessage("noLogin");
//            writer.write(JSON.toJSONString(noLogin));
//            writer.flush();
//            writer.close();
//            return false;
//        }
//        //TODO 查看当前用户是否有访问目标方法的权限 已知：这里是可以获取到访问的目标的方法的
//        //获取访问的目标方法
//        HandlerMethod method = (HandlerMethod)handler;
//        //查看目标方法上是否加了注解
//        PreAuthorize methodAnnotation = method.getMethodAnnotation(PreAuthorize.class);
//        //获取到的注解不为空
//        if(methodAnnotation != null){
//            //访问方法需要的sn
//            String sn = methodAnnotation.value();
//            //查询出当前用户有哪些permiison的sn
//            Logininfo lf = (Logininfo)logininfo;
//            List<String> sns = permissionMapper.loadPermissionSnByLoginInfoId(lf.getId());
//            //判断查询出来的sn是否包含目标方法的sn
//            if(!sns.contains(sn)){
//                //不包含那么就表示没有权限访问
//                response.setContentType("application/json;charset=utf-8");
//                response.setCharacterEncoding("utf-8");
//                //获取响应流
//                PrintWriter writer = response.getWriter();
//                //创建Ajaxresult对象
//                AjaxResult noLogin = AjaxResult.me().setSuccess(false).setMessage("没有权限访问！！！");
//                writer.write(JSON.toJSONString(noLogin));
//                writer.flush();
//                writer.close();
//                return false;
//            }
//        }
//        //如果有就放行，并且刷新过期时间
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        return true;
//    }
}
